import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import { Message } from 'element-ui'
import routes from './routes'
Vue.use(VueRouter)



const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

let flag = true
router.beforeEach(async (to, from, next) => {
  if (to.path != '/login') {

    if (!store.state.tokenObj.token) {
      Message({
        message: '请先登录',
        type: 'warning'
      });
      next('/login')
    } else {
      let route = await store.state.routeModule.routeList
      if (flag && route.length != 0) {
        route.forEach(item => {
          item.component = getComponents(item.name)
          router.addRoute('Home', item)
        })
        flag = false
        next({
          ...to,
          replace: true
        })
      }
      next()
    }

  } else {
    next()
  }
})

function getComponents(path) {
  return () => import(`@/components/${path}`)
}
export default router

